<template>
  <!-- 工时维护店端-经销商端页面 -->
  <div>
    <!--条件筛选-->
    <TopFilter ref="topFilter" :list="topFilterList" :cols="3" labelWidth="85" @filterChange="changeHandle" @onCollapse="collapseHandle"></TopFilter>
    <!--操作 -->
    <button-area :style="{ paddingLeft: '80px' }"></button-area>
    <!-- 列筛选-->
    <FilterTable ref="table" columnsRef="repair-labourHour-index" :pageSize="20" :columns="columns" :fetchapi="fetchApi" :params="fetchParams" :datakey="'rows'" :onColumnsChange="columns => (this.columns = columns)" :onRowSelectChange="selectData">
      <!--列操作-->
      <template slot="controls">
        <el-button size="small" type="primary" icon="el-icon-plus" @click="addEstimate">新增工时</el-button>
        <AjaxButton size="small" type="primary" :click="sendDownClick">下发</AjaxButton>
        <AjaxButton size="small" type="primary" :click="labourDistributeClick">下载</AjaxButton>
        <AjaxButton size="small" type="primary" :click="batchUpdate.bind(this,'10031001')">批量启用</AjaxButton>
        <AjaxButton size="small" type="primary" :click="batchUpdate.bind(this,'10031002')">批量停用</AjaxButton>
        <el-button size="small" type="primary" icon="el-icon-upload" @click="exportClick">导出模板</el-button>
        <multiuse-button size="small" icon="el-icon-upload" @click="showImportFun()">Ecxel导入</multiuse-button>
      </template>

    </FilterTable>

    <!--抽屉 -->
    <Drawer :visible.sync="estimate" :title="dialogTitle" :width="1100" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <labourHourInfo :seriesList="seriesList" :modelList="modelList" :type="handleType" :row="formData" @close="closeEstimate" />
    </Drawer>

    <BaseDialog :visible.sync="showChooseModel" title="车型选择" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <chooseModel @close="closeChooseModelDialog" />
    </BaseDialog>
    <BaseDialog :visible.sync="showImport" :closable="false" icon="el-icon-upload" title="导入" width="800px" destroyOnClose :containerStyle="{ height: 'calc(100% - 120px)', overflow: 'auto', paddingBottom: '60px' }">
      <importExcel @close="showImport = false" @importclose="editSave()" :url='`${config.uploadUrl}/api/dmscloud.repair/basedata/repairProject/importRepairItem`'/>
    </BaseDialog>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import dictCode from '@/utils/dictCode';
import { exportExcelFile } from '@/utils';
import { getSeries } from '@/api/repair/estimateExtension';
import { getLabourHourList, labourDistribute, batchUpdate, importRepairItem, exportRepairItem, getAllUser } from '@/api/repair/repairBusiness/labourHour/index.js';
import labourHourInfo from './labourHourInfo';
import chooseModel from './chooseModel';
import { getListService, exportRepair, exportRepairModel, updateStatesRepairItem, getCarSeries, getAllCarModels, sendDown } from '@/api/claim/dealer/AuthMaintenance';
import config from '@/assets/js/config';
import importExcel from './importExcel';
// 延保订单查询
export default {
  name: 'repair-labourHour-index',
  components: { labourHourInfo, chooseModel,importExcel },
  mixins: [dictionary],
  data() {
    return {
      config: config,
      form: {
        fileList: []
      },
      fetchParams: { 'labourCode': '', 'labourName': '', 'itemStatus': '', 'modelCode': '', xhrAbort: false },
      dialogTitle: '',
      fetchApi: getListService,
      columns: this.createTableColumns(),
      handleType: '',
      formData: {},
      tableData: [],
      selectFlag: false,
      topFilterList: this.createTopFilterList(),
      estimate: false,
      estimatequery: '',
      showChooseModel: false,
      exportLoading: false,
      seriesList: [],//车系数组
      modelList: [],//车型数组
      showImport: false,
    };
  },

  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
    this.getAllUser();
    this.getCarModelData();
  },
  methods: {
    async getAllUser() {
      let res = await getAllUser();
      if (res.resultCode === 200) {
        let allUser = res.data.map(x => ({
          text: x.employeeName,
          value: x.userId + ''
        }));
        this.columns.find(x => x.dataIndex === 'updateBy').dictItems = allUser;
      }
    },
    // 导入成功事件
    handleUploadChange(e) {
      console.log('导入文件上传成功', e.length);
      this.excleLog = e
      if (e.length > 0) {
        this.loading = false;
        this.$notify.success({ title: '提示信息', message: '导入成功!!!' });
        this.fetchParams = Object.assign({}, this.fetchParams);

      }
    },
    editSave() {
      this.showImport = false;
      this.fetchParams = Object.assign({}, this.fetchParams);
    },
    exportClick() {
      this.$confirm('此操作将下载excel模板, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.exportLoading = true;
        exportRepairModel().then(res => {
          exportExcelFile(res.data, '工时模板');
          this.exportLoading = false;
        });
      });
    },
    // Excel更新导入
    showImportFun() {
      this.showImport = true;
    },
    importClick() { },
    // 批量启用/停用
    async batchUpdate(start) {
      if (!this.tableData.length) {
        this.$notify.error({ title: '提示信息', message: '请至少选择一条数据！！！' });
        return;
      }
      let itemIds = [];
      this.tableData.forEach(x => {
        itemIds.push(x.itemId);
      });
      let res = await updateStatesRepairItem({ itemStuatus: start }, itemIds);
      if (res.resultCode === 200) {
        this.$notify.success({ title: '提示信息', message: '操作成功！！' });
        this.fetchParams = Object.assign({}, this.fetchParams);
      }
    },
    async sendDownClick() {
      let itemIds = [];
      this.tableData.forEach(x => {
        itemIds.push(x.itemId);
      });
      let res = await sendDown();
      if (res.resultCode === 200) {
        this.$notify.success({ title: '提示信息', message: '下发成功！！' });
        this.$refs.table.DO_REFRESH();
      }

    },
    async labourDistributeClick() {
      this.fetchParams = { 'labourCode': '', 'labourName': '', 'itemStatus': '', 'modelCode': '', ...this.fetchParams }
      for (let item in this.fetchParams) {
        if (item != 'xhrAbort') {
          this.fetchParams[item] = this.fetchParams[item] ? this.fetchParams[item] : '';
        }
      }

      this.exportLoading = true;
      exportRepair(this.fetchParams).then((res) => {
        exportExcelFile(res.data, '工时查询');
        this.exportLoading = false;
      });
    },
    //获取车型车系
    getCarData(type) {
      let arr = [];
      let tempArr = [];
      getSeriesAndModels(type).then(res => {
        if (res.data) {
          if (type === 'series') {
            res.data.forEach(function (item, i) {
              if (item.SERIES_CODE && !tempArr.includes(item.SERIES_CODE)) {
                arr.push({ text: item.SERIES_CODE, value: item.SERIES_CODE });
                tempArr.push(item.SERIES_CODE);
              }
            })
            this.seriesList = arr;
          } else if (type === 'model') {
            res.data.forEach(function (item, i) {
              if (item.MODEL_LABOUR_CODE && !tempArr.includes(item.MODEL_LABOUR_CODE)) {
                arr.push({ text: item.MODEL_LABOUR_CODE, value: item.MODEL_LABOUR_CODE });
                tempArr.push(item.MODEL_LABOUR_CODE);
              }
            })
            this.modelList = arr;
          }
        }
      })
      return arr
    },

    getCarSeriesData() {
      let dataArr = [];
      let tempArr = [];
      getCarSeries().then((res) => {
        if (res.resultCode === 200) {
          res.data.forEach((item) => {
            if (item.SERIES_NAME && !tempArr.includes(item.SERIES_NAME)) {
              tempArr.push(item.SERIES_NAME);
              dataArr.push({ text: item.SERIES_NAME, value: item.SERIES_CODE, id: item.SERIES_ID });
            }
          });
          this.seriesList = dataArr;
        }
      });
      return dataArr;
    },

    getCarModelData(code, type, isTopFilter = false) {
      console.log(code, type)
      this.topFilterList.find(item => item.fieldName === 'modelCode').initialValue = '';
      let series = this.seriesList.find(item => item.text === code || item.value === code);
      let dataArr = [];
      console.log(series)
      // if (series && series.id) {
      getAllCarModels().then(res => {
            if (res.resultCode === 200){
              res.data.forEach((item) =>{
                this.topFilterList.find(item => item.fieldName === 'modelCode').itemList = res.data.map(x => ({ text: x.MODEL_NAME, value: x.MODEL_CODE1 }));
                dataArr.push({ text: item.MODEL_NAME, value: item.MODEL_CODE1 })
              })
            }
         });
      this.modelList = dataArr;
      // if (res.resultCode === 200) {
      //   if (type == 'edit' && isTopFilter) {
      //     this.topFilterList.find(item => item.fieldName === 'modelCode').itemList = res.data.map(x => ({ text: x.MODEL_NAME, value: x.MODEL_CODE1 }));
      //   }
      //   res.data.forEach((item) => {
      //     dataArr.push({ text: item.MODEL_NAME, value: item.MODEL_CODE1 })
      //   })
      // }
      // }
    },


    createTopFilterList() {
      return [
        {
          type: 'INPUT',
          label: '工时代码',
          fieldName: 'labourCode',
          placeholder: '请输入...'
        },
        {
          type: 'INPUT',
          label: '工时名称',
          fieldName: 'labourName',
          placeholder: '请输入...'
        },
        {
          type: 'SELECT',
          label: '工时状态',
          fieldName: 'itemStatus',
          placeholder: '请选择...',
          itemList: this.createDictList('1003')
        },

        // {
        //   type: 'SELECT',
        //   label: '车系',
        //   fieldName: 'seriesCode',
        //   placeholder: '请选择...',
        //   initialValue: '',
        //   itemList: this.getCarSeriesData(),
        //   change: (val) => {
        //     console.log(val, this.topFilterList);
        //     if (val) {
        //       this.getCarModelData(val, 'edit', true);
        //     } else {
        //       this.topFilterList.find(item => item.fieldName === 'modelCode').itemList = [];
        //       this.topFilterList.find(item => item.fieldName === 'modelCode').initialValue = '';
        //     }
        //
        //   }
        // },
        {
          type: 'SELECT',
          label: '车型',
          fieldName: 'modelCode',
          placeholder: '请选择...',
          itemList: [],
        },
        {
          type: 'SELECT',
          label: '是否下发',
          fieldName: 'downTag',
          placeholder: '请选择...',
          itemList: this.createDictList('1004')
        },
        // {
        //   type: 'INPUT',
        //   label: '车型',
        //   fieldName: 'modelCode',
        //   placeholder: '请选择...',
        //   itemList: [],
        //   unitRender: () => {
        //     return (
        //       <div>
        //         <el-button icon="el-icon-search" onClick={() => this.openModelDialog()}></el-button>
        //       </div>
        //     );
        //   }
        // }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          minWidth: '100',
          render: (props, h) => {
            return (
              <div>
                <el-button disabled={props.row.itemStatus === 10031001} size="mini" type="text" onClick={() => this.emitFun(props.row, 'edit')}>
                  编辑
                </el-button>
                <el-button size="mini" type="text" onClick={() => this.emitFun(props.row, 'show')}>
                  明细
                </el-button>
              </div>
            );
          }
        },
        {
          title: '状态',
          dataIndex: 'itemStatus',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1003'),
          render: props => {
            return <span>{this.createDictText(props.row.itemStatus, '1003')}</span>;
          }
        }, {
          title: '工时代码',
          dataIndex: 'labourCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '工时名称',
          dataIndex: 'labourName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        // {
        //   title: '车系',
        //   dataIndex: 'seriesCode',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input'
        // },
        {
          title: '车型',
          dataIndex: 'modelLabourCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '索赔工时',
          dataIndex: 'stdLabourHour',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '是否下发',
          dataIndex: 'downTag',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1004'),
          render: props => {
            return <span>{this.createDictText(props.row.downTag, '1004')}</span>;
          }
        },
        {
          title: '修改人',
          dataIndex: 'updateBy',
          width: 150,
          sorter: true
        },
        {
          title: '修改时间',
          dataIndex: 'updateAt',
          width: 150,
          dateFormat: 'yyyy-MM-dd HH:mm:ss',
          sorter: true
        }
      ];
    },

    emitFun(val, type) {
      this.getCarModelData(val.seriesCode, type, false);
      this.handleType = type;
      this.dialogTitle = `工时信息`;
      this.formData = val;
      this.estimate = true;

    },

    addEstimate() {
      // 新建
      this.handleType = 'add';
      this.showHandler();
    },
    showHandler() {
      // 显示
      this.dialogTitle = `工时信息`;
      this.estimate = true;
    },
    selectData(val) {
      this.tableData = val;
      if (val.length == 0) {
        this.selectFlag = false;
      } else {
        this.selectFlag = true;
      }
    },
    changeHandle(val) {
      // this.fetchParams = Object.assign({}, val);
      this.fetchParams = Object.assign({}, this.fetchParams, val, { xhrAbort: false });
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },

    closeEstimate(val, type) {
      // 关闭
      this.estimate = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    closeChooseModelDialog(param) {
      this.showChooseModel = false;
      if (param.length) {
        this.topFilterList.find(x => x.fieldName === 'modelCode').initialValue = param[0].modelCode;
      }
    },
    // openModelDialog() {
    //   this.showChooseModel = true;
    // }
  }
};
</script>

<style lang="less" scoped></style>
